/********************************************************************************
 * Project Name		[JavaEE_Components]
 * File Name     	[SendingTextMail.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package javamail.mail;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.junit.Before;
import org.junit.Test;

import javamail.utils.MailConstants;
import javamail.utils.PasswordUtils;

/**
 * 使用SMTP协议发送纯文本邮件
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class SendingTextMail {

	// 发件人
	private static String emailSender = "javamail_sns@sina.com";

	// 收件人
	private static String emailRecipient = "18505106250@163.com";

	// 初始化连接邮件服务器的会话信息
	private static Properties properties = null;

	@Before
	public void init() {
		properties = new Properties();
		properties.setProperty("mail.transport.protocol", MailConstants.PROTOCOL_SMTP);
		properties.setProperty("mail.smtp.host", MailConstants.SMTP_HOST_OF_SINA);
		properties.setProperty("mail.smtp.port", MailConstants.SMTP_PORT_OF_SINA);
		properties.setProperty("mail.smtp.auth", String.valueOf(MailConstants.IS_AUTHORIZATION_NEED));
		properties.setProperty("mail.debug", String.valueOf(MailConstants.IS_DEBUG_MOD_ENABLED));
	}

	/**
	 * 发送简单的文本邮件
	 * 
	 * @throws Exception
	 */
	public static void sendTextMail() throws Exception {
		// 创建Session实例
		Session session = Session.getDefaultInstance(properties);
		// 创建MimeMessage实例
		MimeMessage message = new MimeMessage(session);
		// 设置发件人
		message.setFrom(new InternetAddress(emailSender));
		// 设置邮件主题
		message.setSubject("JavaMail - 简单文本文件");
		// 设置收件人
		message.setRecipient(RecipientType.TO, new InternetAddress(emailRecipient));
		// 设置发送时间
		message.setSentDate(new Date());
		// 设置纯文本内容为邮件正文
		message.setText("使用JavaMail发送纯文本文件");
		// 保存并生成最终的邮件内容
		message.saveChanges();
		// 获得Transport实例
		Transport transport = session.getTransport();
		// 打开连接
		transport.connect(emailSender, PasswordUtils.readPassword(emailSender));
		// 将message对象传递给transport对象, 将邮件发送出去
		transport.sendMessage(message, message.getAllRecipients());
		// 关闭连接
		transport.close();
	}

	@Test
	public void testSendTextMail() throws Exception {
		sendTextMail();
	}
}
